#include "prepare.h"

Prepare::Prepare(QObject *parent) :
    QObject(parent)
{
    smena = Fourth;
    dateTime = QDateTime::currentDateTime().addDays(-3);
    smenaTime=timeKnow();
    SearchList.append({0,"3241.04","H2","ppm"});
    SearchList.append({1,"3241.01","CO","ppm"});
    SearchList.append({2,"3261","CH4","%"});
    SearchList.append({3,"1322","Sv","m/s"});
    SearchList.append({4,"3264","O2","%"});
    listMrParser();
    databaseUp();
    buildWatchMap();
    buildResult();
}

Prepare::~Prepare()
{
    db.close();
}

int Prepare::databaseUp()
{
    db = QSqlDatabase::addDatabase("QODBC");
    db.setDatabaseName("Driver={SQL SERVER};Server=192.168.0.199;Database=Adroit_DB;Trusted_Connection=yes;");
    if (!db.open()){

    }
    return 1;
}

int Prepare::listMrParser()
{
    QFile file("settings.ini");
    if(file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QString _s;
        QStringList _lst_001;
        while (!file.atEnd()) {
            _s = file.readLine();
            if ( _s.contains("controllers"))
                _lst_001.append(file.readLine());
            if ( _s.contains("servname"))
                srvNam.append(file.readLine());
            if ( _s.contains("sqlname"))
                dbNam.append(file.readLine());
            if ( _s.contains("sqlpas"))
                srvPass.append(file.readLine());
        }
        file.close();

        QStringList _lst_002;
        QStringList _lst_003;
        foreach (QString _var, _lst_001) {
            _lst_002 = _var.split(",");
            foreach(QString _str, _lst_002)
            {
                if (!_str.contains("-"))
                    _lst_003.append(_str);
                else
                {
                    QStringList _t;
                    _t = _str.split("-");
                    for (int c = _t[0].toInt() ; c<_t[1].toInt()+1 ; c++) {
                        _lst_003.append(QString::number(c));
                    }
                }
            }
            kontrolersLists.append(_lst_003);
            _lst_003.clear();
        }
        //  qDebug()<<kontrolersLists;
    }
    else
    {
        qDebug()<<file.errorString();
    }
    return 1;
}

int Prepare::buildResult()
{
    //QList<QMap<QString,QList<short int>>> itemList;
    QString _qs;
QList<Item> _l;
   // qDebug()<<descList.length();
    int _c = 0;
    typedef QMap<QString,QList<short int>> _Type;
    foreach (_Type _m_001, itemList)
    {
        QMapIterator<QString, QList<short int>> i(_m_001);
        while (i.hasNext()) {
            i.next();
            foreach (short int _ch, i.value())
            {
                Item _t;
                int _i_001 =typeList[_c].value(i.key()+"_"+QString::number(_ch));
                _t.design = SearchList[_i_001].design;
                _t.type = SearchList[_i_001].type;
                _t.unit = SearchList[_i_001].unit;
                _t.desc = descList[_c].value(i.key()+"_"+QString::number(_ch));
                _t.data = averageVal(i.key(),_ch);
                _l.append(_t);
            }
        }
        resultList.append(_l);
        _l.clear();
        _c++;
    }

    //  qDebug()<<resultList;
    qDebug()<<"Done!";
    return 1;
}

int Prepare::buildWatchMap()
{
    QString _n;
    QString _sq;
    QSqlQuery _q;
    QMap<QString,QString> _map_001;
    QMap<QString,QList<short int>> _map_002;
    QMap<QString,int> _map_003;
    foreach (QStringList _lst_001, kontrolersLists) {
        foreach(QString _str_001, _lst_001)
        {
            QList<short int> _lst_002;
            for(int _c_001 = 1; _c_001 < 9; _c_001++)
            {
                //  qDebug()<<_str_001<<":"<<_c_001;
                _n = _str_001 + "_" + QString::number(_c_001);
                _sq = "SELECT TOP 1 descr_val FROM ChangeSensorDescr WHERE K_ch='K"+_n+"' ORDER BY DateTimeChange DESC ";
                _q.setForwardOnly(true);
                if ( _q.exec(_sq) )
                {
                    _q.first();
                    int _c =0;
                    foreach(searchL _str_002, SearchList){
                        // qDebug()<<_str_002<<":"<<_str_001;
                        if(_q.value(0).toString().contains(_str_002.design))
                        {
                            _map_003.insert(_n,_c);
                            _map_001.insert( _n,_q.value(0).toString());
                            _lst_002.append(_c_001);
                            //  qDebug()<<"cont";
                            break;
                        }
                        _c++;
                    }
                }
            }
            _map_002.insert(_str_001,_lst_002);
        }
        descList.append(_map_001);
        itemList.append(_map_002);
        typeList.append(_map_003);
        _map_001.clear();
        _map_002.clear();
        _map_003.clear();
    }
    // qDebug()<<itemList;
    return 1;
}


bool Prepare::kHealthy()
{

}

bool Prepare::chGood()
{

}

QList<float> Prepare::averageVal(const QString&_kr, const short int& _ch)
{
    QSqlQuery _q;
    _q.setForwardOnly(true);
    QList<float> _lf;
    QString _qs;
    float _t = 0;
    for (int i = 0; i < smenaTime.length(); i++){
        _qs
                = "SELECT ch"
                +QString::number(_ch)
                +"_val"
                +" FROM Adroit_K"
                + _kr
                +" WHERE TimestampStr > '"
                +smenaTime[i].toString("yyyy-MM-dd hh:mm:ss.zzz")
                +"' AND TimestampStr < '"
                +smenaTime[i].addSecs(3600).toString("yyyy-MM-dd hh:mm:ss.zzz")
                +"'";
        //  qDebug()<<_qs;
        if ( _q.exec(_qs) )
        {
            register float _f =0 ;
            int _i = 0;
            _q.first();

            do
            {
                _f = _f + _q.value(0).toFloat();
                _i++;
            }
            while (_q.next());
            _lf.append( _f/_i );
            _t = _t +_f/_i;
            if(smenaTime.length() == i+1)
                _lf.append( _t/smenaTime.length() );
        }
        else
        {
            _lf.append( -1 );
        }
    }
    //qDebug()<<_lf;  
    return _lf;
}

QList<QDateTime> Prepare::timeKnow(  )
{

    QList<QDateTime> _lst;
    switch (smena) {
    case First:
        dateTime.setTime(QTime::fromString("08:00:00"));
        break;
    case Second:
        dateTime.setTime(QTime::fromString("14:00:00"));
        break;
    case Third:
        dateTime.setTime(QTime::fromString("20:00:00"));
        break;
    case Fourth:
        dateTime.setTime(QTime::fromString("02:00:00"));
        dateTime = dateTime.addDays(1);
        break;
    default:
        dateTime.setTime(QTime::fromString("08:00:00"));
        break;
    }
    for(int _c = 0; _c<6;_c++)
        _lst.append(dateTime.addSecs(3600*_c));
    return _lst;
}
void Prepare::getResultList()
{
    emit  result(resultList);
}
